package com.itboye.lottery.activity.football

import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.itboye.bylibrary.listener.MyClickListener
import com.itboye.lottery.R
import com.itboye.lottery.activity.WebActivity
import com.itboye.lottery.activity.ZqBetListActivity
import com.itboye.lottery.adapter.base.MyExpandableListAdapter
import com.itboye.lottery.alert.ByAlert
import com.itboye.lottery.base.BaseActivity
import com.itboye.lottery.bean.FootballMatchBean
import com.itboye.lottery.enums.LotteryType
import com.itboye.lottery.popupwindow.MyLotteryMenuPopUpWindow
import com.itboye.lottery.presenter.UserPresenter
import com.itboye.lottery.retrofit.ResponseCallback
import com.itboye.lottery.utils.BetSelectMatches
import com.itboye.lottery.utils.BetSelectMatches.hashSet
import com.itboye.lottery.utils.BetSelectMatches.map
import com.itboye.lottery.utils.ConstUrl
import kotlinx.android.synthetic.main.activity_football_main.*
import org.json.JSONObject
import java.io.Serializable


class FootballMainActivity : BaseActivity(), ResponseCallback {

    private var type: Int = 0
    var isClickTitle: Boolean = false
    var popUpWindow: MyLotteryMenuPopUpWindow? = null
    var userPresenter: UserPresenter = UserPresenter(this)
    var lay_transroot: LinearLayout? = null
    var toolbar_delete: TextView? = null//清除已选
    var toolbar_hiti: TextView? = null
    var toolbar_confirm: TextView? = null
    var lottery = arrayListOf(LotteryType.HUNTOU, LotteryType.SPF, LotteryType.RSPF, LotteryType.ZJQ, LotteryType.BF, LotteryType.BQC)
    var lotteryType: LotteryType = lottery[0]

    companion object {
        var activity: FootballMainActivity? = null
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_football_main
    }

    override fun initData() {
        activity = this
        initTitleBar()
        bindTl_Vp()
        initialData()
        initPoupwindow()
    }

    private var names: Array<out String>? = null

    private fun initPoupwindow() {
        names = resources.getStringArray(
                R.array.jczq_types_name_list)
        val types = resources.getStringArray(R.array.jczq_types_list)
        popUpWindow = MyLotteryMenuPopUpWindow(this, names, types, 0, AdapterView.OnItemClickListener { parent, view, position, id ->
            //            closeLoadingLayout()
            pager = position
            this.lotteryType = lottery[position]
            setTitle(names!![position])
            popUpWindow!!.notifyDataSetChanged()
            if (popUpWindow!!.isShowing) {
                popUpWindow!!.dismiss()
            }
//                DataUtil.getJCZQMatchInfoDG(jczqData)//胜平负
//            } else {
//                DataUti//
//////            if (pager == 6) {l.getJCZQMatchInfo(jczqData)//胜平负
//            }
            adapter?.setPager(pager)
            clearSelctCache()
            expandAll()
//            if (zq_jczqChilds.size() <= 0)
//                showEmptyLayout("暂无比赛~", R.mipmap.img_blank_match)
        }, PopupWindow.OnDismissListener {
            //            startAnimation(ivTitleIcon, R.anim.rotate_180_360)
        })
    }

    fun expandAll() {
        if (adapter == null) return
        for (i in 0 until adapter!!.groupCount) {// 默认全部展开
            expand_lv.collapseGroup(i)
            expand_lv.expandGroup(i)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        clearSelctCache()
    }

    fun clearSelctCache() {
        if (BetSelectMatches.map != null) {
            BetSelectMatches.map.clear()
        }
        if (BetSelectMatches.hashSet != null) {
            BetSelectMatches.hashSet.clear()
        }
        if (adapter != null) {
            adapter?.caculateTotalSelectMatches()
        }
    }

    fun notifyData() {
        if (adapter!=null) {
            adapter?.notifyDataSetChanged()
        }

    }

    private var adapter: MyExpandableListAdapter? = null

    private fun initialData() {
//        adapter = MyExpandableListAdapter(this, dataset)
//        expand_lv.setAdapter(adapter)
    }

    private fun initTitleBar() {
        setTitle("混合投注", MyClickListener {
            setTitleRightDrawble(when (isClickTitle) {
                true -> {
                    R.mipmap.trangle_down
                }
                false -> {
                    R.mipmap.trangle_up
                }
            })
            isClickTitle = !isClickTitle
            if (!popUpWindow!!.isShowing) {
                popUpWindow!!.setPager(pager!!)
                popUpWindow!!.setOnDismissListener {
                    isClickTitle = !isClickTitle
                    setTitleRightDrawble(R.mipmap.trangle_down)
                }
                popUpWindow!!.showMyAsDropDown(lay_transroot)
            }
        })
        rightTextValue("玩法说明", MyClickListener {
            startActivity(Intent(this, WebActivity::class.java).putExtra("title", "玩法说明").putExtra("url", ConstUrl.play_method_url + "?type=" + ConstUrl.TYPE_FOOTBALL))
        })
    }

    private var pager: Int = 0
    private fun bindTl_Vp() {
        sr_refresh.autoRefresh()
        sr_refresh.setOnRefreshListener {
            getMatchData()
        }
//        orderFragments = ArrayList()
//        orderFragments!!.add(BascketballFragment())
//        orderFragments!!.add(BascketballFragment())
//        orderFragments!!.add(BascketballFragment())
//        vp_football.adapter = CommonPagerAdapter(this, orderFragments, R.array.football_title, supportFragmentManager)
//        vp_football.offscreenPageLimit = 5
//        tl_football.setupWithViewPager(vp_football)
//        vp_football.setCurrentItem(intent.getIntExtra("order_position", 0), false)
    }

    fun getMatchData() {
//        if (adapter!=null) {
        map.clear()
        hashSet.clear()
//        }
        userPresenter.geFootBallMatch()//获取近期足球比赛
    }


    override fun onClick(p0: View?) {
        when (p0!!.id) {
            R.id.tv_actionbar_title -> {

            }
            R.id.toolbar_delete -> {
                if (adapter == null) {
                    ByAlert.alert("当前没有比赛数据！")
                    return
                }
                adapter!!.deleteSelect()
            }
            R.id.toolbar_confirm -> {
                if (adapter == null) {
                    ByAlert.alert("当前没有比赛数据！")
                    return
                }
                var isDg = isDG()
                if ((adapter!!.matchCount < 1 && isDg) || ((!isDg) && adapter!!.matchCount < 2)) {
                    ByAlert.alert("至少选择2场比赛！")
                    return
                }
//                if (adapter!!.matchCount < 2) {
//                    ByAlert.alert("至少选择2场比赛！")
//                    return
//                }
                if (ZqBetListActivity.activity != null) {
                    ZqBetListActivity.activity.finish()
                }
                startActivity(Intent(this, ZqBetListActivity::class.java)
                        .putExtra("map", adapter!!.map as (Serializable))
                        .putExtra("pager", pager)
                        .putExtra("isDg", isDg)
                        .putExtra("lotteryType", lotteryType)
                        .putExtra("arrayList", adapter!!.zqBetListItemArrayList)
                        .putExtra("old_arrayList", data))//将初始数据传入
            }
            else -> {
            }
        }
    }

    private fun isDG(): Boolean {
        var isDg = false
        var iterator = adapter!!.map.keys
        var dgCount = 0 //单关数量
        var fdgCount = 0//非单关数量
        for (s in iterator) {
            val get: Map<String, String> = adapter!!.map[s]!!
            var iterator = get.keys
            iterator.forEachIndexed { index, s ->
                if (s.split("_")[5] == "1") {
                    isDg = true
                    dgCount++
//                    return isDg
                } else {
                    fdgCount++
                    isDg = false
                }
            }
        }
        if (dgCount > 0 && fdgCount <= 0) {//全单关
            isDg = true
        } else if (dgCount > 0 && fdgCount > 0) {//既有单关又有非单关
            isDg = false
        } else if (dgCount <= 0) {//全非单关
            isDg = false
        }
        return isDg
    }

    private var data = ArrayList<FootballMatchBean>()

    override fun success(o: Any, requestSuccessType: String) {
        sr_refresh.isRefreshing = false
        if (requestSuccessType == userPresenter.geFootBallMatch_SUCCESS) {
            //返回的O 为LinkMap格式，需要转换为json数据
            var gson = GsonBuilder().enableComplexMapKeySerialization().create()
            val jsonString = gson.toJson(o)
            data = ArrayList()
            //重新组装数据
            try {
                var jsonObject = JSONObject(jsonString)
                var iterator = jsonObject.keys()
                while (iterator.hasNext()) {
                    var dataMatchInfoArray = ArrayList<FootballMatchBean.MatchInfo>()
                    var footballMatchBean = FootballMatchBean()
                    var key = iterator.next()
                    val keyJSON = jsonObject.getJSONArray(key)
                    footballMatchBean.groupTime = (key)
                    for (i in 0 until keyJSON.length()) {
                        var job = keyJSON.getJSONObject(i) // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                        val type2 = object : TypeToken<FootballMatchBean.MatchInfo>() {
                        }.type
                        var bean = gson.fromJson<FootballMatchBean.MatchInfo>(job.toString(), type2)
                        dataMatchInfoArray.add(bean)
                    }
                    footballMatchBean.matchList = dataMatchInfoArray
                    data.add(footballMatchBean)
                    Log.v("response_data", "足球赛事keyJSON：___________ " + data.size)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                ByAlert.alert("暂无比赛数据")
            }
            adapter = MyExpandableListAdapter(this, data)
            expand_lv.setAdapter(adapter)
            adapter!!.setPager(pager)
            expandAll()
            adapter!!.caculateTotalSelectMatches()
        }
    }

    override fun fail(code: Int, msg: Any, requestErrorType: String) {
        sr_refresh.isRefreshing = false
        Log.v("response_data", "error：$msg")
    }


}
